package com.ljh.server.handler;

import com.ljh.message.GroupCreateRequestMessage;
import com.ljh.message.GroupCreateResponseMessage;
import com.ljh.server.session.Group;
import com.ljh.server.session.GroupSession;
import com.ljh.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.Set;

/**
 * @author: Themberfue
 * @date: 2025/5/29 22:47
 * @description:
 */
@ChannelHandler.Sharable
public class GroupCreateRequestHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        Set<String> members = msg.getMembers();

        // ? 群管理器
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Group group = groupSession.createGroup(groupName, members);
        if (group == null) {
            // TODO 1. 发送成功消息
            ctx.writeAndFlush(new GroupCreateResponseMessage(true, "群聊创建成功"));
            // TODO 2. 给其他成员发送拉入群聊消息
            List<Channel> membersChannel = groupSession.getMembersChannel(groupName);
            for (Channel channel : membersChannel) {
                channel.writeAndFlush(new GroupCreateResponseMessage(true, "您已被拉入群聊：" + groupName));
            }
        } else {
            ctx.writeAndFlush(new GroupCreateResponseMessage(false, "群聊创建失败，群聊已经存在"));
        }
    }
}
